<template>
  <div class="content">
    <div class="w">
      <back-btn />
      <div class="space-between mb24">
        <div>
          <span>已加入成员数：</span><span style="color: #3C7BFF;">{{ pageObj.total }}/{{ peopleLimit }}</span>
        </div>
        <a-button type="primary" @click="openInviteModal">
          <template #icon>
            <plus-outlined :style="{ color: '#fff' }" />
          </template>
          邀请成员
        </a-button>
      </div>
      <a-table
        bordered
        row-key="id"
        height="50vh"
        :scroll="{
          y: '60vh'
        }"
        :data-source="tableData"
        :columns="columns"
        :pagination="{
          pageSize: pageObj.pageSize,
          current: pageObj.pageNum,
          total: pageObj.total,
          showTotal: (total: number) => `共${total}条数据`,
          showSizeChanger: true,
          showQuickJumper: true,
          onChange: handlePageChange
        }"
      >
      </a-table>
    </div>
    <a-modal
      :visible="inviteVisible"
      title="邀请成员"
      @ok="handleCopy"
      @cancel="inviteVisible = false"
      cancel-text=" "
      ok-text="复制链接"
    >
      <div class="mb8">
        链接最长生效 7 天。<br />
        若团队已达人数上限，则链接失效。
      </div>
    </a-modal>

    <a-modal
      :visible="visible"
      :title="form.isEdit ? '编辑名称' : '移出团队'"
      :confirm-loading="confirmLoading"
      @ok="handleOk"
      @cancel="closeModal"
    >
      <template v-if="form.isEdit">
        <div class="mb8">已选择用户： {{ form.customerName }}</div>

        <a-radio-group v-model:value="form.roleType">
          <a-radio :value="ROLE_TYPE.成员">{{ ROLE_TYPE[2] }}</a-radio>
          <a-radio :value="ROLE_TYPE.管理员">{{ ROLE_TYPE[1] }}</a-radio>
        </a-radio-group>
      </template>
      <template v-else> 确定要移除该成员({{ form.customerName }})吗？ </template>
    </a-modal>
  </div>
</template>

<script setup lang="ts">
import { computed, h, onMounted, ref } from 'vue'
import { PlusOutlined } from '@ant-design/icons-vue'
import { message as msgHelper } from 'ant-design-vue'
import { useTable } from '@/hook/useTable'
import {
  apiChangeRole,
  apiTeamMemberList,
  apiRemoveMember,
  apiGenerateInviteInfo
} from '@/api/manage'
import { useClipboard } from '@vueuse/core'
import { ROLE_TYPE } from '@/const'
import { useUserInfoStore } from '@/stores/modules/userInfo'

const userStore = useUserInfoStore()

// 解构出列表数据和loading
const { tableData, loading, pageObj, handlePageChange, getList, updatedParams } = useTable({
  apiFn: apiTeamMemberList,
  isPageable: true,
  params: { teamId: userStore.userInfo.currentTeamId },
  immediate: true,
  callback: (tableData) =>  {
    const ownerItem = tableData?.rows?.find((c) => c.roleType === ROLE_TYPE.所有者)
    if(ownerItem) {
      ownerId.value = ownerItem?.customerId
    }
    return tableData
  }
})
const peopleLimit = computed(() => {
  return tableData.value[0]?.peopleLimit || 0
})

const form = ref<{ roleType?: ROLE_TYPE; customerName?: string; id: string; isEdit: boolean }>({
  roleType: 0,
  customerName: '',
  id: '',
  isEdit: false
})
const visible = ref(false)
const confirmLoading = ref(false)
const handleOk = async () => {
  confirmLoading.value = true
  console.warn(form.value.roleType, '007')
  let res
  if (form.value.isEdit) {
    // 更改用户角色接口
    res = await apiChangeRole({
      roleType: form.value.roleType || ROLE_TYPE.成员,
      teamCustomerId: form.value.id
    })
  } else {
    // 移出用户接口
    res = await apiRemoveMember({ teamCustomerId: form.value.id })
  }
  const { data } = res
  msgHelper.info(data.message)
  confirmLoading.value = false
  closeModal()
  getList()
}
const closeModal = () => {
  form.value = {
    roleType: 0,
    customerName: '',
    id: '',
    isEdit: false
  }
  visible.value = false
}

const inviteVisible = ref(false)

const openInviteModal = () => {
  inviteVisible.value = true
}

const { text, copy, copied, isSupported } = useClipboard()

const handleCopy = async () => {
  const {
    data: { entity: inviteInfoId }
  } = await apiGenerateInviteInfo({ teamId: userStore.userInfo.currentTeamId })
  // console.warn(inviteInfoId, 'data')
  copy(`${location.host}/invite/${inviteInfoId}`)
  msgHelper.success('复制成功')
}

const ownerId = ref('')
const columns = ref<Array<any>>([
  {
    title: '名称',
    dataIndex: 'customerName',
    width: 145
  },
  {
    title: '手机号',
    dataIndex: 'phone',
    width: 118
  },
  {
    title: '角色',
    dataIndex: 'roleType',
    width: 75,
    customRender: ({ record }: { record: any }) => {
      return ROLE_TYPE[record.roleType]
    }
  },
  {
    title: '邀请人',
    dataIndex: 'invitePhone',
    width: 118,
    customRender: ({ record }: { record: any }) => {
      return record.invitePhone || '--'
    }
  },
  {
    title: '加入时间',
    dataIndex: 'createdTime',
    width: 170
  },
  // {
  //   title: '最近登录时间',
  //   dataIndex: 'lastedLoginTime',
  //   width: 200
  // },
  {
    title: '管理',
    dataIndex: 'action',
    width: 160,
    // fixed: 'right',
    customRender: ({ record }: { record: any }) => {
      // const record: AuditVO = opt.record as AuditVO
      // if(record.isSuperManager) return <Space />
      if (record.customerId === userStore.id || record.roleType === ROLE_TYPE.所有者) return
      let renderAction = []
      if (userStore.id === ownerId.value) {
        renderAction.push(
          h(
            'a',
            {
              style: {
                'margin-right': '16px'
              },
              onClick: () => {
                form.value.id = record.id || ''
                form.value.customerName = record.customerName || ''
                form.value.isEdit = true
                form.value.roleType = record.roleType || ROLE_TYPE.成员
                visible.value = true
              }
            },
            '更改角色'
          )
        )
      }
      renderAction.push(
        h(
          'span',
          {
            style: {
              color: '#FC5D50',
              cursor: 'pointer'
            },
            onClick: () => {
              form.value.id = record.id || ''
              form.value.customerName = record.customerName || ''
              form.value.isEdit = false
              visible.value = true
            }
          },
          '移出团队'
        )
      )
      return h('span', {}, renderAction)
    }
  }
])
</script>

<style lang="scss" scoped>
.content {
  background-color: #fff;
  min-height: 100vh;
  .w {
    position: relative;
    width: 800px;
    margin: 0 auto;
    padding-top: 110px;
    .back {
      position: absolute;
      right: 0;
      top: 24px;
    }
    .avatar {
      font-size: 18px;
      color: #3d3d3d;
      img {
        display: block;
        width: 100px;
        height: 100px;
        border-radius: 50%;
        box-shadow: 0px 5px 13px 0px rgba(234, 238, 241, 0.4);
      }
    }
  }
}
:deep() {
  .ant-table-tbody > tr > td {
    border-right: 0px !important;
    padding: 12px 8px 12px 24px;
    color: #0D1C2E;
  }
  .ant-table-thead > tr > th {
    border-right: 0px !important;
    color: #0D1C2E;
    background-color: #F7F9FC;
    padding: 12px 24px;
    font-weight: bold;
  }
  .ant-table.ant-table-bordered > .ant-table-container {
    border-left: 0px;
  }
}
</style>
